#include "FrameCorrect.h"
#include "ui_FrameCorrect.h"

#include <QFileDialog>



FrameCorrect::FrameCorrect(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FrameCorrect),
    _D_data{Singleton<DebugToolData>::get()}
{
    ui->setupUi(this);
    this->setWindowTitle("龙骨融合");
}

FrameCorrect::~FrameCorrect()
{
    delete ui;
}

void FrameCorrect::transAndReplace(RobotPos p)
{
    auto BaseP = p>RobotTCP::UPLOAD;
    posInTool(BaseP,RorateMatrix.first,RorateMatrix.second);    // 在此处转换为工件坐标系的位置

    std::string query = "replace INTO " + _curIndex.db_name + "(seamid,index1,pos)VALUES(?,?,?)";
    // SQLHelper::GetBlade()->_p_tr->prepare(query,_curIndex.seamid,_curIndex.index1,BaseP.toStr());    // 插入到数据库
}

int FrameCorrect::updateIndex(std::string f)
{
    int ret = -1;
    std::regex e("([[:w:]]+)-([[:w:]]+)-([[:w:]]+)-([[:w:]]+)");
    std::smatch m;
    bool found = regex_search(f, m, e);
    if(found){
         _curIndex.db_name = m.str(2) ;
         _curIndex.seamid = atoi(m.str(3).c_str())  ;
         _curIndex.index1 = atoi(m.str(4).c_str())  ;
    }else {
        std::cout << BOLDYELLOW << "验证数据正则表达式出现错误！"<< RESET<<std::endl;
    }

    try {
        auto t = SQLHelper::GetBlade()->_p_tr->Get({_curIndex.db_name},{"enabled"},{"seamid",std::to_string(_curIndex.seamid)
                         ,"index1",std::to_string(_curIndex.index1)});
        ret = t.at(0).toInt();
    }catch(...){
        qWarning()<<BOLDRED<<__FUNCTION__<<"数据库可能没有该字段，请检查当前数据库版本!"<<RESET;
    }
    return ret;
}

void FrameCorrect::appendStr(QString f)
{
    ui->textBrowser->append(f);
    ui->textBrowser->moveCursor(QTextCursor::End);
}




void FrameCorrect::on_pb_opendir_clicked()
{
    QString dir = QFileDialog::getExistingDirectory(this, tr("打开格点目录"),
                            "grid",QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
    ui->le_dir->setText(dir);
}


/**
 * @brief FrameCorrect::on_pb_run_clicked
 * @details
 * 执行顺序;
 * [1] 获取数据库中这个表里的数据是否修正过？
 *      【true】 不执行
 *      【false】执行修正算法
 * [2] 执行修正算法后
 *      【true】调用翠柳的算法
 *      【false】开启手动纠偏
 * @warning
 * @target  获取当前文件夹的线型及统计结果
 */
void FrameCorrect::on_pb_run_clicked()
{
    //std::string curDir = ui->le_dir->text().toStdString();
    appendStr("-------------------------------------------------------------------------------");
    std::string curDir=ui->le_dir->text().section('/', -1).toStdString();
    int ret = updateIndex(curDir);
    if( -1 == ret){
        appendStr("从文件夹获取内容失败!");
    }else if(1 == ret){
        appendStr("该数据已经进行过修正!");
    }else{
        auto r = CalcProvider::inputADir(curDir);
        // 如果获取到的结果不是预期
        //    if(!r.first){
                // ui->pb_self->setEnabled(true);   // 开启手动纠偏功能
        //    }else{    ui->pb_gen->setEnabled(true);  // 开启自动纠偏功能
        //}
    }
}

// 手动纠偏
void FrameCorrect::on_pb_self_clicked()
{
    std::string name = ui->le_dir->text().toStdString();
    auto ret = ImgProvider::GetInstance()->findRealPos(_D_data->taskGrid.at(name));
    _curReal = ret.first;
    the_mis  = ret.second;
    ui->textBrowser->append("*****************纠正后********************");
    ui->textBrowser->append("1.纠正结果");
    ui->textBrowser->append(QString::fromStdString(_curReal.toStr()));
    ui->textBrowser->append("2.纠正偏差值");
    ui->textBrowser->append(QString::fromStdString(the_mis.toStr()));
    ui->textBrowser->append("******************************************");
}

/**
 * @brief FrameCorrect::on_pb_write_clicked
 * @details 写入真实的pos到数据库中
 * @param TCP类型必须是CAMERA，相机中心点的POS
 */
void FrameCorrect::on_pb_write_clicked()
{
    transAndReplace(_curReal);
}

/**
 * @brief FrameCorrect::on_pb_gen_clicked
 * @target 调用自动计算真实点
 */
void FrameCorrect::on_pb_gen_clicked()
{

}
